package com.example.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class WuSrtToLrcConverter {
    private static final Pattern SRT_BLOCK_REGEX = Pattern.compile(
        "(\\d+)[^\\S\\r\\n]*[\\r\\n]+" +
        "(\\d{2}:\\d{2}:\\d{2},\\d{3,4})[^\\S\\r\\n]*-->[^\\S\\r\\n]*(\\d{2}:\\d{2}:\\d{2},\\d{3,4})[^\\S\\r\\n]*[\\r\\n]+" +
        "([\\s\\S]*)"
    );

    public static void main(String[] args) {
        File file = new File("/Users/xiaoxu.wu/Desktop/20220617.srt");
        srtFileToLrc(file);
    }

    private static void srtFileToLrc(File file) {
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            StringBuilder strIn = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                strIn.append(line).append("\n");
            }

            String strInText = strIn.toString();
            String[] blocksIn = strInText.replace("\r\n", "\n").split("\n\n");

            StringBuilder strOut = new StringBuilder();
            for (String block : blocksIn) {
                String blockOut = srtBlockToLrc(block);
                if (blockOut != null) {
                    strOut.append(blockOut);
                }
            }

            try (BufferedWriter writer = new BufferedWriter(new FileWriter(file.getAbsolutePath().replace(".srt", ".lrc")))) {
                writer.write(strOut.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String srtBlockToLrc(String block) {
        Matcher matcher = SRT_BLOCK_REGEX.matcher(block);
        if (!matcher.find()) {
            return null;
        }

        String num = matcher.group(1);
        String ts = matcher.group(2).substring(3).replace(",", ".");
        String te = matcher.group(3).substring(3).replace(",", ".");
        String content = matcher.group(4).replace("\n", " ");

        return String.format("[%s]%s\n[%s]\n", ts, content, te);
    }



}
